package org.example.fancystudy.ThreadLocalStudy;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

/**
 * @author chaigq
 * @version 1.0
 * @date 2023/2/21 16:38
 */
class MyObject{
    @Override
    protected void finalize() throws Throwable{
        // finalize的通常目的是在对象被不可撤销地丢弃之前执行清理操作。
        System.out.println("-------invoke finalize method~!!!");
    }
}
public class ReferenceDemo {
    public static void main(String[] args) {
//        MyObject myObject = new MyObject();
//        System.out.println("gc before: "+myObject);
//        myObject = null;
//        System.gc();//人工开启GC，一般不用
//        try {
//            TimeUnit.MILLISECONDS.sleep(300);
//        }catch (InterruptedException e){
//            e.printStackTrace();
//        }
//        System.out.println("gc after: " + myObject);
//        ==================================================

//        MyObject myObject = new MyObject();
//        SoftReference<MyObject> softReference = new SoftReference<MyObject>(myObject);
//        System.gc();
//        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
//        System.out.println("-----gc after内存够用: "+softReference.get());
//
//        // 创建一个大对象
//        try {
//            Byte[] bytes = new Byte[20 * 1024 * 1024];
//        }catch (Exception e){
//            e.printStackTrace();
//        }finally {
//            System.out.println("-----gc after内存够用: "+softReference.get());
//        }

//        ==================================================

        //MyObject myObject = new MyObject();
        WeakReference<MyObject> weakReference = new WeakReference<>(new MyObject());
        System.out.println("-----gc before 内存够用: "+weakReference.get());
        System.gc();
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.println("-----gc after 内存够用: "+weakReference.get());
    }
}
